package exchanger;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;

public class ExchangeTest
{
    private static final Exchanger<String> exgr = new Exchanger<String>();

    private static ExecutorService threadPool = Executors.newFixedThreadPool(2);

    public static void main(String[] args)
        throws InterruptedException
    {
        System.out.println(test3(6, i -> i * i));
    }

    public static int test3(int i, Function<Integer, Integer> function)
    {
        return function.apply(i);
    }

    /**
     * CountDownLatch
     * @author zhuxiang
     * @date 下午8:21 2021/2/23
     * @param:
     * @return void
     */
    public static void test2()
        throws InterruptedException
    {
        CountDownLatch count = new CountDownLatch(2);
        threadPool.execute(() ->
        {
            try
            {
                Thread.currentThread().sleep(2000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            count.countDown();
            System.out.println("线程1结束..");
        });

        threadPool.execute(() ->
        {
            try
            {
                Thread.currentThread().sleep(6000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            count.countDown();
            System.out.println("线程2结束..");
        });
        count.await();
        System.out.println("任务结束！");
        threadPool.shutdown();
    }

    /**
     * exchanger
     * @author zhuxiang
     * @date 下午8:15 2021/2/23
     * @param:
     * @return void
     */
    public void test1()
    {
        threadPool.execute(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    // A录入银行流水数据
                    String A = "银行流水A";
                    exgr.exchange(A);  // 进入阻塞状态，等待数据交换
                    System.out.println("exchange a..");
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        });
        threadPool.execute(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    // B录入银行流水数据
                    String B = "银行流水B";
                    Thread.currentThread().sleep(6000);

                    String A = exgr.exchange(B);
                    System.out.println("A和B数据是否一致：" + A.equals(B) + ", A录入的是：" + A + ", B录入是：" + B);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        });
        threadPool.shutdown();
    }
}
